package cc.rengu.oltp.utility.util;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.*;
import javax.mail.internet.*;
import java.io.File;
import java.io.Serializable;
import java.util.List;
import java.util.Map;
import java.util.Properties;

/**
 * 邮件发送工具类
 * Created by 王成 on 2018/11/28.
 */
public class EmailUtil implements Serializable {
    public static String auth = "mail.smtp.auth";
    public static String host = "mail.smtp.host";
    public static String protocol = "mail.transport.protocal";
    public static String port = "mail.smtp.port";
    public static String userName = "mail.auth.user";
    public static String password = "mail.auth.password";
    public static String strttls = "mail.smtp.starttls.enable";
    public static String sslcheck = "mail.smtp.ssl.checkserveridentity";
    public static String ssltrust = "mail.smtp.ssl.trust";
    public static String socketclass = "mail.smtp.socketFactory.class";
    public static String socketfallback = "mail.smtp.socketFactory.fallback";
    public static String socketport = "mail.smtp.socketFactory.port";
    public static String sslenable = "mail.smtp.ssl.enable";
    public static String mailsubject = "mail.subject";

    /**
     * 发送邮件
     *
     * @param emailAttrMap 邮件配置属性
     * @param toUsers      邮件接收人
     * @param ccUsers      邮件抄送人
     * @param subject      邮件主题
     * @param content      邮件内容
     * @param attachFiles  邮件附件
     */
    public static void sendEmail(Map<String, String> emailAttrMap, List<String> toUsers, List<String> ccUsers, String subject, String content, List<String> attachFiles) throws Exception {
        Properties properties = new Properties();
        properties.put(host, emailAttrMap.get(host));
        properties.put(port, emailAttrMap.get(port));
        properties.put(auth, (null != emailAttrMap.get(auth)) ? emailAttrMap.get(auth) : "true");
        properties.put(protocol, (null != emailAttrMap.get(protocol)) ? emailAttrMap.get(protocol) : "smtp");
        properties.put(strttls, (null != emailAttrMap.get(strttls)) ? emailAttrMap.get(strttls) : "true");
        properties.put(sslcheck, (null != emailAttrMap.get(sslcheck)) ? emailAttrMap.get(sslcheck) : "false");
        properties.put(ssltrust, (null != emailAttrMap.get(ssltrust)) ? emailAttrMap.get(ssltrust) : emailAttrMap.get(host));
        properties.put(socketclass, emailAttrMap.get(socketclass));
        properties.put(socketfallback, (null != emailAttrMap.get(socketfallback)) ? emailAttrMap.get(socketfallback) : "false");
        properties.put(socketport, emailAttrMap.get(port));
        properties.put(sslenable, (null != emailAttrMap.get(sslenable)) ? emailAttrMap.get(sslenable) : "true");

        Session session = Session.getInstance(properties, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(emailAttrMap.get(userName), emailAttrMap.get(password));
            }
        });
        session.setDebug(false);
        MimeMessage message = new MimeMessage(session);
        /* 发件人 */
        InternetAddress from = new InternetAddress(emailAttrMap.get(userName));
        message.setFrom(from);
        /* 收件人 */
        if (null != toUsers) {
            InternetAddress[] sendTo = new InternetAddress[toUsers.size()];
            for (int i = 0; i < toUsers.size(); i++) {
                sendTo[i] = new InternetAddress(toUsers.get(i));
            }
            message.setRecipients(MimeMessage.RecipientType.TO, sendTo);
        }
        /* 抄送人 */
        if (null != ccUsers) {
            InternetAddress[] sendCc = new InternetAddress[ccUsers.size()];
            for (int i = 0; i < ccUsers.size(); i++) {
                sendCc[i] = new InternetAddress(ccUsers.get(i));
            }
            message.setRecipients(MimeMessage.RecipientType.CC, sendCc);
        }
        /* 邮件主题 */
        if (null != subject) {
            message.setSubject(subject);
        } else if (null != emailAttrMap.get(mailsubject) && !emailAttrMap.get(mailsubject).isEmpty()) {
            message.setSubject(emailAttrMap.get(mailsubject));
        } else {
            message.setSubject("电子邮件" + emailAttrMap.get(userName));
        }
        /* 邮件正文及附件 */
        Multipart multipart = new MimeMultipart();
        BodyPart contentPart = new MimeBodyPart();
        if (null != content) {
            contentPart.setContent(content, "text/html;charset=UTF-8");
            multipart.addBodyPart(contentPart);
        }
        if (null != attachFiles && attachFiles.size() > 0) {
            for (String fileName : attachFiles) {
                BodyPart attachmentBodyPart = new MimeBodyPart();
                DataSource source = new FileDataSource(new File(fileName));
                attachmentBodyPart.setDataHandler(new DataHandler(source));
                attachmentBodyPart.setFileName(fileName.substring(fileName.lastIndexOf(File.separator) + 1));
                multipart.addBodyPart(attachmentBodyPart);
            }
        }
        message.setContent(multipart);
        /* 保存邮件 */
        message.saveChanges();
        /* SMTP验证 验证用户名及密码 */
        Transport transport = session.getTransport();
        transport.connect(emailAttrMap.get(host), emailAttrMap.get(userName), emailAttrMap.get(password));
        /* 发达邮件 */
        transport.sendMessage(message, message.getAllRecipients());
        if (null != transport) {
            transport.close();
        }
    }
}